package com.banzhi.shop.activity;

import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.banzhi.shop.MyApp;
import com.banzhi.shop.R;
import com.banzhi.shop.adapter.CommonHeadAdapter;
import com.banzhi.shop.base.BaseActivity;
import com.banzhi.shop.entity.Group.Datas;
import com.banzhi.shop.entity.Group.GroupShop;
import com.banzhi.shop.entity.Group.ShopGoods;
import com.banzhi.shop.entity.WXshare;
import com.banzhi.shop.model.CallBack.HomeFrgModelCallBack;
import com.banzhi.shop.model.CallBack.WXshareCallBack;
import com.banzhi.shop.model.IGroupShop;
import com.banzhi.shop.model.IHomeFrgModel;
import com.banzhi.shop.model.Impl.GroupShopImpl;
import com.banzhi.shop.model.Impl.HomeFrgModelImpl;
import com.banzhi.shop.model.Impl.WXshareImpl;
import com.banzhi.shop.model.WXshareModel;
import com.banzhi.shop.utils.ASUtils;
import com.banzhi.shop.utils.CustomToast;
import com.banzhi.shop.utils.EndlessRecyclerOnScrollListener;
import com.banzhi.shop.utils.LoadingDialogUtils;
import com.banzhi.shop.utils.NoTokenUtils;
import com.banzhi.shop.utils.NumberUtils;
import com.banzhi.shop.utils.ShareUtils;
import com.banzhi.shop.utils.ToastUtils;
import com.banzhi.shop.utils.Translucent;
import com.squareup.picasso.Picasso;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 推荐店铺
 */
public class GroupShopDetailActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener, IGroupShop.MyCallback, HomeFrgModelCallBack, WXshareCallBack {

    private List<ShopGoods> mData = new ArrayList<>(); // 展示的数据集合
    private GroupShop mGroupShop;
    private SwipeRefreshLayout mRefreshLayout; // 下拉刷新的控件
    private ImageView mBackImage; // 返回的图片
    private TextView mTitleView;
    private RecyclerView mRecyclerView; // 布局控件
    private ImageView imgGroupCover;
    private ImageView imgGroupLogo;
    //  private TextView mTvName;
    private TextView mTvDetail;
    private int position; // adapter 传过来的position 用于删除集合你对应的商品
    private String icon; // 以添加到店铺的状态值
    private CommonHeadAdapter<ShopGoods> mAdapter; // 适配器
    private int page = 1; // 页码
    LinearLayoutManager layoutManager;
    private int brandID;
    private IGroupShop model;
    private IHomeFrgModel mHomeModel;
    private RelativeLayout mEntityLayout;
    private AppBarLayout mAppbarlayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recommend_shop);
        Translucent.setTranslucent(this);
        initView();
        initListener();
        initData();

    }

    private void initData() {
        Intent intent = getIntent();
        if (intent != null) {
            brandID = intent.getIntExtra("brandId", 1);
            mTitleView.setText(intent.getStringExtra("title"));
            // brandID = intent.getStringExtra("brandId");
            Log.d("jiejie", "---商品的ID" + brandID);
        } else {
            finish();
        }
        model.getGroupDetail(brandID, page, this);
    }

    @Override
    protected void onStart() {
        super.onStart();

    }

    private void initListener() {
        mRefreshLayout.setOnRefreshListener(this);
        mBackImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        mRecyclerView.addOnScrollListener(new EndlessRecyclerOnScrollListener(layoutManager) {
            @Override
            public void onLoadMore() {
                page++;
                LoadingDialogUtils.showProgress(GroupShopDetailActivity.this, "正在加载,请稍后~");
                model.getGroupDetail(brandID, page, GroupShopDetailActivity.this);
            }
        });
    }

    private void initView() {

        model = new GroupShopImpl();
        wxmodel = new WXshareImpl();
        // mHomeModel = new HomeFrgModelImpl();
        mBackImage = (ImageView) findViewById(R.id.iv_back);
        mRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeLayout);
        mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        imgGroupCover = (ImageView) findViewById(R.id.item_group_cover);
       imgGroupLogo = (ImageView) findViewById(R.id.item_group_logo);
        //mTvName = (TextView) findViewById(R.id.item_group_name);
        mEntityLayout = (RelativeLayout) findViewById(R.id.rl_nodata);
        mTitleView = (TextView) findViewById(R.id.iv_title);
        mTvDetail = (TextView) findViewById(R.id.item_group_detail);
        mRefreshLayout.setColorSchemeResources(R.color.themeColor);
        mRefreshLayout.setProgressBackgroundColorSchemeResource(R.color.colorWhite);
        layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        mRecyclerView.setLayoutManager(layoutManager);
        mAppbarlayout = (AppBarLayout) findViewById(R.id.appbar);
        mAppbarlayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                if (verticalOffset >= 0) {
                    mRefreshLayout.setEnabled(true);
                } else {
                    mRefreshLayout.setEnabled(false);
                }
            }
        });


    }

    /**
     * 刷新
     */
    @Override
    public void onRefresh() {
        page = 1;
        LoadingDialogUtils.showProgress(this, "正在加载,请稍后~");
        model.getGroupDetail(brandID, page, this);
    }

    /**
     * 请求成功
     */
    @Override
    public void onSuccess(Object object) {
        if (mRefreshLayout.isRefreshing()) {
            mRefreshLayout.setRefreshing(false);
        }
        if (page == 1) {
            mGroupShop = ((Datas) object).getBrand();
            mData.clear();
        }
        showTopPlace();
        mData.addAll(((Datas) object).getGoods());
        if (mData.size() == 0) {
            mEntityLayout.setVisibility(View.VISIBLE);
        } else {
            mEntityLayout.setVisibility(View.GONE);
        }
        showView();
        LoadingDialogUtils.dismiss();
    }

    /**
     * 展示列表数据R.layout.item_group_shop,
     */
    private void showView() {
        if (mAdapter == null) {
            mAdapter = new CommonHeadAdapter<ShopGoods>(this, R.layout.item_group_shop_detail, mData) {
                @Override
                public void convert(ViewHolder holder, final ShopGoods data, final int position) {
                    // 标题
                    holder.setText(R.id.tv_title, data.getTitle());

                    // 库存
                    holder.setText(R.id.item_detail_stock, "库存" + data.getTotal());
                    // 价格
                    if (data.getBegin_price().equals(data.getEnd_price())) {
                        holder.setText(R.id.tv_price, data.getBegin_price());
                    } else {
                        holder.setText(R.id.tv_price, data.getMarketprice());
                    }
                    // 利润
                    holder.setText(R.id.tv_zhuan, data.getProfit());
                    // 在售人数
                    holder.setText(R.id.item_detail_num, "　在售人数" + data.getSharebtn());
                    // 商品图片
                    if (ASUtils.isCanUse(data.getImages().get(0))) {
                        Picasso.with(MyApp.context).load(data.getImages().get(0)).placeholder(R.mipmap.zhanweitu2).into(holder.getImageView(R.id.iv_image));
                    }
                    if ("1".equals(MyApp.loginMessage.getString("isagent",""))) {                             //店长专区
                        holder.getImageView(R.id.iv_delete).setVisibility(View.VISIBLE);
                        holder.getView(R.id.ll_pinpaituan).setVisibility(View.VISIBLE);
                        holder.getImageView(R.id.iv_share).setVisibility(View.VISIBLE);
                    } else {
                        holder.getImageView(R.id.iv_delete).setVisibility(View.INVISIBLE);
                        holder.getView(R.id.ll_pinpaituan).setVisibility(View.INVISIBLE);
                        holder.getImageView(R.id.iv_share).setVisibility(View.INVISIBLE);
                        //非店主专区
                    }
                    // 是不是加入店铺了
                    if ("0".equals(data.getIcon())) {
                        holder.getImageView(R.id.iv_delete).setImageResource(R.mipmap.jian1);
                        holder.getImageView(R.id.iv_delete).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                LoadingDialogUtils.showProgress(GroupShopDetailActivity.this, "正在加载,请稍后");
                                if (mHomeModel == null) {
                                    mHomeModel = new HomeFrgModelImpl();
                                }
                                // 删除店铺
                                mHomeModel.deleteGoods(data.getId() + "", null, GroupShopDetailActivity.this);
                                GroupShopDetailActivity.this.position = position;
                                GroupShopDetailActivity.this.icon = data.getIcon();
                            }
                        });
                    } else if ("1".equals(data.getIcon())) {
                        holder.getImageView(R.id.iv_delete).setImageResource(R.mipmap.jia1);
                        holder.getImageView(R.id.iv_delete).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                LoadingDialogUtils.showProgress(GroupShopDetailActivity.this, "正在加载,请稍后");
                                if (mHomeModel == null) {
                                    mHomeModel = new HomeFrgModelImpl();
                                }
                                mHomeModel.AddDianpu(data.getId() + "", GroupShopDetailActivity.this);
                                GroupShopDetailActivity.this.position = position;
                                GroupShopDetailActivity.this.icon = data.getIcon();
                            }
                        });
                    }
                    // 保存
                    holder.getImageView(R.id.iv_saveimages).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            if ("1".equals(data.getIsagentgoods())) {
                                ToastUtils.makeToastShort("该商品为注册商品");
                            } else {
                                Intent intent = new Intent(GroupShopDetailActivity.this, CommodityDetailsActivity.class);
                                intent.putExtra("id", data.getId() + "");
                                intent.putExtra("type", "1");
                                startActivity(intent);
                            }
                        }
                    });
                    // 分享
                    holder.getImageView(R.id.iv_share).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            if ("1".equals(data.getIsagentgoods())) {
                                ToastUtils.makeToastShort("该商品为注册商品");
                            } else {
                                wxURL = null;
                                showSharePopupwindow(data);
                                GroupShopDetailActivity.this.position = position;
                            }
                        }
                    });
                }

                @Override
                public void headconvert(HeaderViewHolder holder) {

                }
            };
            mRecyclerView.setAdapter(mAdapter);
        } else {
            mAdapter.notifyDataSetChanged();
        }
        mAdapter.setOnItemClickListener(new CommonHeadAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                if ("1".equals(mData.get(position).getIsagentgoods())) {
                    ToastUtils.makeToastShort("该商品为注册商品");
                } else {
                    Intent intent = new Intent(GroupShopDetailActivity.this, CommodityDetailsActivity.class);
                    intent.putExtra("id", mData.get(position).getId() + "");

                    startActivity(intent);
                }
            }
        });
    }

    // 展示顶部的数据
    private void showTopPlace() {
        if (page > 1) return;
        if (ASUtils.isCanUse(mGroupShop.getCover())) {
            Picasso.with(MyApp.context).load(mGroupShop.getCover()).placeholder(R.mipmap.vp_zhanweitu).into(imgGroupCover);
        }
       // mTvName.setText(mGroupShop.getName());
        mTvDetail.setText(mGroupShop.getDetail());
        if (ASUtils.isCanUse(mGroupShop.getLogo())) {
            Picasso.with(MyApp.context).load(mGroupShop.getLogo()).placeholder(R.mipmap.zhanweitu1).into(imgGroupLogo);
        }
    }

    /**
     * 解析失败
     */
    @Override
    public void onError(Object object) {
        if (mRefreshLayout.isRefreshing()) {
            mRefreshLayout.setRefreshing(false);
        }
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(GroupShopDetailActivity.this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }

    @Override
    public void getDataSuccess(Object object) {

    }

    @Override
    public void getDataError(Object object) {

    }

    /**
     * 添加店铺成功
     *
     * @param object
     */
    @Override
    public void AddDianpuSuccess(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        CustomToast.showToast(GroupShopDetailActivity.this, "上架成功", jsonObject.optString("res"));
        if ("0".equals(icon)) {
            mData.get(position).setIcon("1");
        } else {
            mData.get(position).setIcon("0");
        }
        mAdapter.notifyItemChanged(position);
    }

    /**
     * 添加店铺解析失败
     */
    @Override
    public void AddDianpuError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }

    /**
     * 移除店铺成功
     */
    @Override
    public void deleteSuccess(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        CustomToast.showToast(this, "下架成功", jsonObject.optString("res"));
        if ("0".equals(icon)) {
            mData.get(position).setIcon("1");
        } else {
            mData.get(position).setIcon("0");
        }
        mAdapter.notifyItemChanged(position);
    }

    /**
     * 移除店铺解析失败
     */
    @Override
    public void deleteError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }

    /**
     * 用于存储该商品的
     */
    private String wxURL;
    private WXshareModel wxmodel;
    private static final int PENGYOUQUAN = 1;
    private static final int WEIXINHAOYOU = 2;
    private static final int LIANJIE = 3;
    private static final int ERWEIMA = 4;

    /**
     * 展示分享的popupwindow
     */
    private void showSharePopupwindow(final ShopGoods data) {
        //设置contentView
        View contentView = LayoutInflater.from(this).inflate(R.layout.popupwindow_share_goods, null);
        final PopupWindow popWindow = new PopupWindow(contentView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true);
        popWindow.setContentView(contentView);
        popWindow.setAnimationStyle(R.style.AnimBottom);

        popWindow.setFocusable(true);
        popWindow.setOutsideTouchable(false);// 设置允许在外点击消失
        //设置各个控件的点击响应
        ImageView ivchacha = (ImageView) contentView.findViewById(R.id.iv_chacha);
        TextView tvprice = (TextView) contentView.findViewById(R.id.tvmoney);
        TextView tvpricetwo = (TextView) contentView.findViewById(R.id.tv_money_two);
        LinearLayout llpengyouquan = (LinearLayout) contentView.findViewById(R.id.ll_pengyouquan);
        LinearLayout llweixin = (LinearLayout) contentView.findViewById(R.id.ll_weixing);
        LinearLayout lllianjie = (LinearLayout) contentView.findViewById(R.id.ll_lianjie);
        LinearLayout llerweima = (LinearLayout) contentView.findViewById(R.id.ll_erweima);
        RelativeLayout rlbackground = (RelativeLayout) contentView.findViewById(R.id.rl_background);
        LinearLayout ll = (LinearLayout) contentView.findViewById(R.id.ll);
        rlbackground.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow.dismiss();
            }
        });
        ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        if (data != null) {
            tvprice.setText(NumberUtils.DecimalFormat(data.getProfit()));
            tvpricetwo.setText(NumberUtils.DecimalFormat(data.getProfit()));
            lllianjie.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (wxURL == null) {
                        LoadingDialogUtils.showProgress(GroupShopDetailActivity.this, "正在加载,请稍后~");
                        wxmodel.getData(data.getId() + "", null, LIANJIE, GroupShopDetailActivity.this);
                    } else {
                        ShareUtils.copyLianjie(GroupShopDetailActivity.this, wxURL);
                    }
                }
            });
            llerweima.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (wxURL == null) {
                        LoadingDialogUtils.showProgress(GroupShopDetailActivity.this, "正在加载,请稍后~");
                        wxmodel.getData(data.getId() + "", null, ERWEIMA, GroupShopDetailActivity.this);
                    } else {
                        ShareUtils.ereima3(GroupShopDetailActivity.this, data.getTitle(), data.getMarketprice(), null, null, null, data.getThumb(), wxURL);
                    }
                }
            });
            llweixin.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (wxURL == null) {
                        LoadingDialogUtils.showProgress(GroupShopDetailActivity.this, "正在加载,请稍后~");
                        wxmodel.getData(data.getId() + "", null, WEIXINHAOYOU, GroupShopDetailActivity.this);
                    } else {
                        ShareUtils.wxshare(data.getTitle(), data.getImages().get(0), "全球十佳网商联合出品。匠心工厂，源头供货，正品优品，尽在半职。", wxURL);
                    }
                }
            });
            llpengyouquan.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (wxURL == null) {
                        LoadingDialogUtils.showProgress(GroupShopDetailActivity.this, "正在加载,请稍后~");
                        wxmodel.getData(data.getId() + "", null, PENGYOUQUAN, GroupShopDetailActivity.this);
                    } else {
                        ShareUtils.wxPengyouquan(data.getTitle(), data.getThumb(), wxURL);
                    }
                }
            });
        }
        ivchacha.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                wxURL = null;
                popWindow.dismiss();
            }
        });
        ColorDrawable dw = new ColorDrawable(0x70000000);
        popWindow.setBackgroundDrawable(dw);
        popWindow.showAtLocation(contentView, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    @Override
    public void ongetWXdataSuccess(Object object, int num) {
        LoadingDialogUtils.dismiss();
        WXshare share = (WXshare) object;
        wxURL = share.getRes();
        if (num == LIANJIE) {
            ShareUtils.copyLianjie(this, wxURL);
        } else if (num == ERWEIMA) {
            ShareUtils.ereima3(this, mData.get(position).getTitle(), mData.get(position).getMarketprice(), null, null, null, mData.get(position).getThumb(), wxURL);
        } else if (num == WEIXINHAOYOU) {
            ShareUtils.wxshare(mData.get(position).getTitle(), mData.get(position).getImages().get(0), "全球十佳网商联合出品。匠心工厂，源头供货，正品优品，尽在半职。", wxURL);
        } else if (num == PENGYOUQUAN) {
            ShareUtils.wxPengyouquan(mData.get(position).getTitle(), mData.get(position).getThumb(), wxURL);
        }
    }

    @Override
    public void ongetWXdataError(Object object, int num) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }
}
